package fr.sedoo.metadata.client.ui.widget.table.snapshot;

import com.google.gwt.cell.client.Cell;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.ui.Image;

import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.widget.DialogBoxTools;
import fr.sedoo.commons.client.widget.table.ImagedActionCell;
import fr.sedoo.commons.client.widget.table.ImagedActionCell.Delegate;
import fr.sedoo.commons.client.widget.table.PreviewCell;
import fr.sedoo.commons.client.widget.table.TableBundle;
import fr.sedoo.commons.shared.domain.HasIdentifier;
import fr.sedoo.commons.shared.domain.IsUrl;
import fr.sedoo.metadata.client.message.MetadataMessage;
import fr.sedoo.metadata.client.ui.widget.table.common.DescribedStringTable;
import fr.sedoo.metadata.shared.domain.misc.IdentifiedDescribedString;

public class SnapshotTable extends DescribedStringTable {

	protected Column<HasIdentifier, String> seeColumn;
	private final Image seeImage = new Image(TableBundle.INSTANCE.view());

	@UiConstructor
	public SnapshotTable(String waterMark, String descriptionWatermark, String addItemText, String valueColumnHeader, String descriptionColumnHeader) {
		super(waterMark, descriptionWatermark, addItemText, valueColumnHeader, descriptionColumnHeader);
	}

	@Override
	protected void initEditColumns() {

		super.initEditColumns();
		Cell<HasIdentifier> seeActionCell = new ImagedActionCell<HasIdentifier>(seeAction, seeImage, CommonMessages.INSTANCE.view());
		seeColumn = new Column(seeActionCell) {

			@Override
			public HasIdentifier getValue(Object object) {
				return (HasIdentifier) object;
			}
		};

		itemTable.addColumn(seeColumn);
		itemTable.setColumnWidth(seeColumn, 30.0, Unit.PX);
	}

	@Override
	protected void initDisplayColumns() {

		super.initDisplayColumns();
		Cell<IsUrl> previewCell = new PreviewCell();
		Column previewColumn = new Column(previewCell) {

			@Override
			public IsUrl getValue(Object object) {
				return (IsUrl) object;
			}
		};

		itemTable.addColumn(previewColumn);
		itemTable.setColumnWidth(previewColumn, 110.0, Unit.PX);
	}

	Delegate<HasIdentifier> seeAction = new Delegate<HasIdentifier>() {

		@Override
		public void execute(final HasIdentifier hasId) {

			IdentifiedDescribedString aux = (IdentifiedDescribedString) hasId;
			if ((aux.getValue() == null) || (aux.getValue().trim().length() == 0)) {
				DialogBoxTools.modalAlert(CommonMessages.INSTANCE.error(), MetadataMessage.INSTANCE.urlAreMandatory());
				return;
			} else {
				DialogBoxTools.popUpImage(CommonMessages.INSTANCE.view(), aux.getValue());
			}

		}

	};

}
